package org.grayrabbit.cms.lisener;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.grayrabbit.cms.freemarker.tpl.config.PopulateFtlData;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;


import freemarker.template.Configuration;

public class FreemarkerListener implements ServletContextListener {

	public void contextDestroyed(ServletContextEvent evt) {
		
	}

	public void contextInitialized(ServletContextEvent evt) {
		ServletContext sc = evt.getServletContext();
		Configuration configuration = loadConfiguration(sc);
		
		Properties props = new Properties();
		
		try {
			props.load( getClass().getResourceAsStream("/tpl.properties") );
		} catch (IOException e) {
			e.printStackTrace();
			throw new ExceptionInInitializerError(e);
		}
		
		ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
		PopulateFtlData.initFreemarkerConfiguration(props, context, configuration);
	}
	
	private Configuration loadConfiguration(ServletContext sc) {
		ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
		return (Configuration) context.getBean("freemarkerConfiguration");
	}
}
